package com.cloud.lan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.lan.api.dto.resp.LanUserResp;
import com.cloud.lan.dao.LanMpCouponMapper;
import com.cloud.lan.dao.LanMpReplyMapper;
import com.cloud.lan.dao.LanMpUserMapper;
import com.cloud.lan.dao.LanUserMapper;
import com.cloud.lan.entity.base.BaseResponse;
import com.cloud.lan.entity.constant.WxDataConstant;
import com.cloud.lan.entity.model.dataobject.*;
import com.cloud.lan.service.ILanUserV2Service;
import com.cloud.lan.service.ILanWxMpService;
import com.cloud.lan.service.tx.wx.config.WxMpConfiguration;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.io.File;
import java.io.InputStream;
import java.util.Date;

import static com.cloud.lan.entity.utils.ConstantInterface.Enum.ConstantNumber.ZERO;

@Slf4j
@Service
public class LanWxMpServiceImpl extends ServiceImpl<LanMpUserMapper, LanMpUserDO> implements ILanWxMpService {
    @Resource
    LanMpUserMapper lanMpUserMapper;
    @Resource
    LanMpReplyMapper lanMpReplyMapper;
    @Resource
    LanMpCouponMapper lanMpCouponMapper;
    @Resource
    WxMpConfiguration wxMpConfiguration;

    @Override
    public BaseResponse<Object> getMpUser(String unionId) {
        LambdaQueryWrapper<LanMpUserDO> luWd = new LambdaQueryWrapper<>();
        luWd.eq(LanMpUserDO::getUnionId, unionId);
        return BaseResponse.success(lanMpUserMapper.selectCount(luWd));
    }

    @Override
    public BaseResponse<Object> save(String openId, String unionId) {
        LambdaQueryWrapper<LanMpUserDO> luWd = new LambdaQueryWrapper<>();
        luWd.eq(LanMpUserDO::getOpenId, openId);
        int cnt = lanMpUserMapper.selectCount(luWd);
        if (cnt == 0) {
            LanMpUserDO mpUserDO = new LanMpUserDO();
            mpUserDO.setOpenId(openId).setUnionId(unionId);
            lanMpUserMapper.insert(mpUserDO);
        }
        return BaseResponse.success();
    }

    @Override
    public BaseResponse<Object> sendKfMsg(String openId, String content) {
        WxMpService wxMpService = wxMpConfiguration.getMpService(WxDataConstant.MPAPPID);
        WxMpKefuMessage kefuMessage = WxMpKefuMessage.TEXT()
                .toUser(openId)
                .content(content) // 消息内容
                .build();
        try {
            // 发送消息
            wxMpService.getKefuService().sendKefuMessage(kefuMessage);
        } catch (WxErrorException e) {
        }
        return BaseResponse.success();
    }

    @Override
    public BaseResponse<Object> sendKfMsg(String openId, String path, String content) {
        WxMpService wxMpService = wxMpConfiguration.getMpService(WxDataConstant.MPAPPID);
        try {
            String resourceName = "/static/img/share.png";
//            // 图片文件
//            File imageFile = new File("/static/img/share.jpg");
//            WxMpMaterial material = new WxMpMaterial();
//
//            material.setFile(imageFile);
            // 使用类加载器获取资源的输入流
            InputStream inputStream = getClass().getResourceAsStream(resourceName);
            if (inputStream == null) {
                throw new RuntimeException("图片资源未找到: " + resourceName);
            }

            // 调用上传图片的API
            WxMediaUploadResult uploadResult = wxMpService.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, "jpg", inputStream);

            // 打印返回的 media_id
            log.info("Media ID: " + uploadResult.getMediaId());
            WxMpKefuMessage kefuMessage = WxMpKefuMessage.MINIPROGRAMPAGE()
                    .toUser(openId)
                    .appId(WxDataConstant.APPID)
                    .pagePath(path)
                    .title(content)
                    .thumbMediaId(uploadResult.getMediaId())
                    .build();
            // 发送消息
            wxMpService.getKefuService().sendKefuMessage(kefuMessage);
        } catch (WxErrorException e) {
        }
        return null;
    }

    @Override
    public LanMpCouponDO getMpCoupon(String openId) {
        LambdaQueryWrapper<LanMpCouponDO> luWd = new LambdaQueryWrapper<>();
        luWd.eq(LanMpCouponDO::getUseOpenId, openId);
        int cnt = lanMpCouponMapper.selectCount(luWd);
        if (cnt == 0) {
            LanMpCouponDO lanMpCouponDO = lanMpCouponMapper.getMpCouponByStatus(0);
            lanMpCouponDO.setStatus(1);
            lanMpCouponDO.setUseOpenId(openId);
            lanMpCouponMapper.updateById(lanMpCouponDO);
            return lanMpCouponDO;
        } else {
            return null;
        }
    }

    @Override
    public String getQrcodeUrl(String scene) {
        WxMpService wxMpService = wxMpConfiguration.getMpService(WxDataConstant.MPAPPID);

        try {
            WxMpQrCodeTicket qrCodeTicket = wxMpService.getQrcodeService().qrCodeCreateLastTicket(scene);
            String ticket = qrCodeTicket.getTicket();
            return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
        } catch (WxErrorException e) {
        }
        return null;
    }

    @Override
    public BaseResponse<Object> startMsg(String openId) {
        LambdaQueryWrapper<LanMpReplyDO> luWd = new LambdaQueryWrapper<>();
        luWd.eq(LanMpReplyDO::getOpenId, openId);
        int cnt = lanMpReplyMapper.selectCount(luWd);
        if (cnt == 0) {
            LanMpReplyDO mpReplyDO = new LanMpReplyDO();
            mpReplyDO.setOpenId(openId);
            lanMpReplyMapper.insert(mpReplyDO);
        }
        return BaseResponse.success();
    }

    @Override
    public BaseResponse<Object> replyMsg(String openId, String content) {
        LambdaQueryWrapper<LanMpReplyDO> luWd = new LambdaQueryWrapper<>();
        luWd.eq(LanMpReplyDO::getOpenId, openId);
        int cnt = lanMpReplyMapper.selectCount(luWd);
        if (cnt > 0) {
            LanMpReplyDO lanMpReplyDO = lanMpReplyMapper.getMpReplyByOpenId(openId);
            if (StringUtils.isBlank(lanMpReplyDO.getContent())) {
                lanMpReplyDO.setContent(content);
                lanMpReplyDO.setReplyTime(new Date());
                lanMpReplyMapper.updateById(lanMpReplyDO);
                sendKfMsg(openId, "感谢您的参与，兰嘉丝汀期待为您呈现更多精彩！");
            }
        }
        return BaseResponse.success();
    }
}
